package ru.spb.osll.myfit.server;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import ru.spb.osll.myfit.server.fixtureiterator.FileFactory;
import fit.Fixture;

public class MyFitClassLoaderFactory {
	private Logger log = Logger.getLogger(getClass());
	private FileFactory m_fileFactory;
	
	public MyFitClassLoaderFactory(FileFactory fileFactory) {
		m_fileFactory = fileFactory;
	}
	
	public URLClassLoader createClassLoader(String... dirNames) {
	  LinkedList<URL> urls = new LinkedList<URL>();
    for (String dirName : dirNames) {
      File dir = m_fileFactory.createFile(dirName);
      String[] jars = dir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
          return name.endsWith(".jar") || name.endsWith(".zip");
        }
      });
      addURLs(urls, dirName, jars);
    }
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), Fixture.class.getClassLoader());
  }
	
	public URLClassLoader createClassLoader(List<URL> listURL, String... dirNames) {
	  LinkedList<URL> urls = new LinkedList<URL>();
	  urls.addAll(listURL);
    
    for (String dirName : dirNames) {
      File dir = m_fileFactory.createFile(dirName);
      String[] jars = dir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
          return name.endsWith(".jar") || name.endsWith(".zip");
        }
      });
      addURLs(urls, dirName, jars);
    } 
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), Fixture.class.getClassLoader());
	
	}  
	private void addURLs(LinkedList<URL> urls, String dir, String[] jars) {
		for(String jar : jars) {
			try {
				urls.add(new URL("file", "localhost", dir + File.separator + jar));
			} catch (MalformedURLException e) {
				log.error("error creating URL", e);
			}
		}
	}
}
